import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/remote_control_service.dart';
import '../core/media_control_event_bus.dart';

/// TV焦点包装组件，用于处理遥控器导航
class TVFocusWrapper extends StatefulWidget {
  final Widget child;
  final bool enableRemoteControl;
  
  const TVFocusWrapper({
    Key? key,
    required this.child,
    this.enableRemoteControl = true,
  }) : super(key: key);
  
  @override
  _TVFocusWrapperState createState() => _TVFocusWrapperState();
}

class _TVFocusWrapperState extends State<TVFocusWrapper> {
  final RemoteControlService _remoteService = RemoteControlService();
  final FocusNode _wrapperFocusNode = FocusNode();
  
  @override
  void initState() {
    super.initState();
    if (widget.enableRemoteControl) {
      _wrapperFocusNode.addListener(_onFocusChange);
      _remoteService.registerFocusNode(_wrapperFocusNode);
    }
  }
  
  @override
  void dispose() {
    if (widget.enableRemoteControl) {
      _wrapperFocusNode.removeListener(_onFocusChange);
      _remoteService.unregisterFocusNode(_wrapperFocusNode);
      _wrapperFocusNode.dispose();
    }
    super.dispose();
  }
  
  void _onFocusChange() {
    if (_wrapperFocusNode.hasFocus) {
      // 当获得焦点时，可以添加视觉反馈
      // 例如改变边框颜色、添加阴影等
    }
  }
  
  @override
  Widget build(BuildContext context) {
    if (!widget.enableRemoteControl) {
      return widget.child;
    }
    
    return RawKeyboardListener(
      focusNode: _wrapperFocusNode,
      autofocus: true,
      onKey: (RawKeyEvent event) {
        if (_remoteService.handleKeyEvent(event)) {
          // 按键已被处理，阻止进一步传播
          return;
        }
        
        // 可以在这里添加其他自定义按键处理
        if (event is RawKeyDownEvent) {
          _handleCustomKeys(event.logicalKey);
        }
      },
      child: Focus(
        focusNode: _wrapperFocusNode,
        child: Container(
          decoration: BoxDecoration(
            border: _wrapperFocusNode.hasFocus
                ? Border.all(color: Theme.of(context).primaryColor, width: 2)
                : null,
            borderRadius: BorderRadius.circular(8),
          ),
          child: widget.child,
        ),
      ),
    );
  }
  
  void _handleCustomKeys(LogicalKeyboardKey key) {
    // 自定义按键处理
    if (key == LogicalKeyboardKey.mediaPlayPause) {
      // 播放/暂停
      debugPrint('播放/暂停按键');
      _broadcastMediaControlEvent(MediaControlEvent.playPause);
    } else if (key == LogicalKeyboardKey.mediaStop) {
      // 停止
      debugPrint('停止按键');
      _broadcastMediaControlEvent(MediaControlEvent.stop);
    } else if (key == LogicalKeyboardKey.mediaRewind) {
      // 快退
      debugPrint('快退按键');
      _broadcastMediaControlEvent(MediaControlEvent.rewind);
    } else if (key == LogicalKeyboardKey.mediaFastForward) {
      // 快进
      debugPrint('快进按键');
      _broadcastMediaControlEvent(MediaControlEvent.fastForward);
    } else if (key == LogicalKeyboardKey.audioVolumeUp) {
      // 音量增加
      debugPrint('音量增加按键');
      _broadcastMediaControlEvent(MediaControlEvent.volumeUp);
    } else if (key == LogicalKeyboardKey.audioVolumeDown) {
      // 音量减少
      debugPrint('音量减少按键');
      _broadcastMediaControlEvent(MediaControlEvent.volumeDown);
    } else if (key == LogicalKeyboardKey.audioVolumeMute) {
      // 静音
      debugPrint('静音按键');
      _broadcastMediaControlEvent(MediaControlEvent.mute);
    } else if (key == LogicalKeyboardKey.mediaTrackNext) {
      // 下一曲/下一个视频
      debugPrint('下一曲按键');
      _broadcastMediaControlEvent(MediaControlEvent.nextTrack);
    } else if (key == LogicalKeyboardKey.mediaTrackPrevious) {
      // 上一曲/上一个视频
      debugPrint('上一曲按键');
      _broadcastMediaControlEvent(MediaControlEvent.previousTrack);
    }
  }

  /// 广播媒体控制事件
  void _broadcastMediaControlEvent(MediaControlEvent event) {
    // 使用事件总线或Provider来广播媒体控制事件
    // 这里使用简单的回调机制，实际项目中可以使用更复杂的事件系统
    MediaControlEventBus.instance.broadcast(event);
  }
}

/// 可聚焦的TV按钮组件
class TVFocusButton extends StatefulWidget {
  final Widget child;
  final VoidCallback? onPressed;
  final VoidCallback? onFocused;
  final bool autofocus;
  
  const TVFocusButton({
    Key? key,
    required this.child,
    this.onPressed,
    this.onFocused,
    this.autofocus = false,
  }) : super(key: key);
  
  @override
  _TVFocusButtonState createState() => _TVFocusButtonState();
}

class _TVFocusButtonState extends State<TVFocusButton> {
  final FocusNode _focusNode = FocusNode();
  final RemoteControlService _remoteService = RemoteControlService();
  
  @override
  void initState() {
    super.initState();
    _focusNode.addListener(_onFocusChange);
    _remoteService.registerFocusNode(_focusNode);
    
    if (widget.autofocus) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _focusNode.requestFocus();
      });
    }
  }
  
  @override
  void dispose() {
    _focusNode.removeListener(_onFocusChange);
    _remoteService.unregisterFocusNode(_focusNode);
    _focusNode.dispose();
    super.dispose();
  }
  
  void _onFocusChange() {
    if (_focusNode.hasFocus && widget.onFocused != null) {
      widget.onFocused!();
    }
  }
  
  void _handleTap() {
    if (widget.onPressed != null) {
      widget.onPressed!();
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Focus(
      focusNode: _focusNode,
      onKey: (node, event) {
        if (event is RawKeyDownEvent &&
            (event.logicalKey == LogicalKeyboardKey.enter ||
             event.logicalKey == LogicalKeyboardKey.select)) {
          _handleTap();
          return KeyEventResult.handled;
        }
        return KeyEventResult.ignored;
      },
      child: GestureDetector(
        onTap: _handleTap,
        child: Container(
          decoration: BoxDecoration(
            color: _focusNode.hasFocus
                ? Theme.of(context).primaryColor.withOpacity(0.1)
                : Colors.transparent,
            border: _focusNode.hasFocus
                ? Border.all(color: Theme.of(context).primaryColor, width: 2)
                : null,
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.all(12),
          child: widget.child,
        ),
      ),
    );
  }
}